package com.cnap.multiclouldmgmt.vm.service;

import com.cnap.multiclouldmgmt.controller.K8sClusterController;
import com.cnap.multiclouldmgmt.model.CommonResult;
import com.cnap.multiclouldmgmt.model.vmScale.ScaleGroupPolicy;
import com.cnap.multiclouldmgmt.repository.master.VMScaleMapper;
import com.cnap.multiclouldmgmt.util.TokenUtils;
import com.cnap.multiclouldmgmt.vm.task.AsyncInvokeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Service
@DependsOn(value = {"msvcDataSourceInitializer","cnapDataSourceInitializer"})
public class VMScale {
    @Autowired
    private VMScaleMapper vmScaleMapper;

    @Autowired
    private AsyncInvokeService asyncInvokeService;

    public static ConcurrentHashMap<String,Integer> scalGroupOverThresholdTime = new ConcurrentHashMap<>();

    //当前正在执行监控的线程
    public static ConcurrentHashMap<String,Thread> currentThreadAndScalePolicyMap = new ConcurrentHashMap<>();

    private final static Logger LOGGER = LoggerFactory.getLogger(K8sClusterController.class);

    /**
     *
     * @throws InterruptedException
     */
    @PostConstruct
    public void scanScalGroup() throws InterruptedException {

        List<ScaleGroupPolicy> vmScaleGroupPolicys = vmScaleMapper.getVmScaleGroupPolicy(TokenUtils.getUserName());
        if(vmScaleGroupPolicys == null || vmScaleGroupPolicys.size() ==0){
            return;
        }
        for(ScaleGroupPolicy policy:vmScaleGroupPolicys){
            asyncInvokeService.exec(policy);
            LOGGER.info("scan a policy from tables,start thread to monitor it");
            Thread.sleep(1000L);
        }
        LOGGER.info("启动弹性伸缩组监控测策略完成");

    }

    /**
     *
     * @param id
     * @return
     * @throws InterruptedException
     */
    public CommonResult<String> addScalePolicy(String id) throws InterruptedException {
        ScaleGroupPolicy policy = vmScaleMapper.queryVmScaleGroupPolicyById(id);
        if(policy == null){
            LOGGER.info("police id {} not exist ",id);
            return  CommonResult.success("");
        }
        scalGroupOverThresholdTime.put(id,0);
        asyncInvokeService.exec(policy);
        LOGGER.info("start a policy thread,id is "+id);
        return  CommonResult.success("add success");
    }

    /**
     *
     * @param id
     * @return
     * @throws InterruptedException
     */
    public CommonResult<String> updateScalePolicy(String id) throws InterruptedException {
        ScaleGroupPolicy policy = vmScaleMapper.queryVmScaleGroupPolicyById(id);
        scalGroupOverThresholdTime.put(id,0);
        Thread thread = currentThreadAndScalePolicyMap.get(id);
        thread.interrupt();
        currentThreadAndScalePolicyMap.remove(id);
        asyncInvokeService.exec(policy);
        LOGGER.info("start update  policy thread,id is "+id);
        return  CommonResult.success("update success");
    }

    /**
     *
     * @param id
     * @return
     * @throws InterruptedException
     */
    public CommonResult<String> deleteScalePolicy(String id) throws InterruptedException {
        LOGGER.info("start delete policy ,thread id is "+id);
//        ScaleGroupPolicy policy = vmScaleMapper.queryVmScaleGroupPolicyById(id);
        scalGroupOverThresholdTime.remove(id);
        Thread thread = currentThreadAndScalePolicyMap.get(id);
        if(thread == null){
            LOGGER.info("police {} 不存在，无需停止该策略 "+id);
            currentThreadAndScalePolicyMap.remove(id);
            return CommonResult.success("delete success");
        }
        thread.interrupt();
        currentThreadAndScalePolicyMap.remove(id);
        LOGGER.info("delete  policy thread,id is "+id);
        return  CommonResult.success("delete success");
    }



}
